#include "CmdUtil.h"
#include "QStringUtil.h"
#include <QProcess>
#include <QDebug>
#include <QStringList>
#include <QMessageBox>
#include <QThread>

CmdUtil::CmdUtil()
{

}

bool CmdUtil::isPortListening(int port) {
    QString portStr = QString::number(port, 10);
    QString strTemp = CmdUtil::runCmd("netstat -ano | findstr " + portStr);
    QStringList sections = strTemp.split(QRegExp("\r\n"));
    QString result = "";
    bool isPortExists = false;
    for (QString section : sections) {
        QString line = QStringUtil::removeAllSpaces(section);
        int index = line.indexOf(QString("TCP0.0.0.0:" + portStr + "0.0.0.0:0LISTENING"));
        if (index >= 0) {
            isPortExists = true;
            break;
        }
    }
    return isPortExists;
}

QString CmdUtil::runCmd(QString cmdStr) {
    QProcess cmd;
    cmd.start("cmd.exe", QStringList()<<"/c"<<cmdStr);
    if (cmd.waitForStarted()) {
        cmd.waitForFinished();
        QString strTemp = QString::fromLocal8Bit(cmd.readAllStandardOutput());
        return strTemp;
    } else {
        qDebug() << "cmd error";
        return QString("");
    }
}

QString CmdUtil::runCmd(QString cmdStr, int timeout) {
    QProcess cmd;
    cmd.start("cmd.exe", QStringList()<<"/c"<<cmdStr);
    if (cmd.waitForStarted()) {
        cmd.waitForFinished(timeout);
        QString strTemp = QString::fromLocal8Bit(cmd.readAllStandardOutput());
        return strTemp;
    } else {
        qDebug() << "cmd error";
        return QString("");
    }
}
